package com.tjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tjl.model.Address;
import com.tjl.service.Impl.AddressServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author TJL
 * @date 2022/5/27
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressServiceImpl service;

    @Autowired
    private JwtUtils jwtUtils;

    @GetMapping("/{id}")
    public CodeMsg getOne(@PathVariable Integer id,@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(service.getById(id));
    }

    @GetMapping
    public CodeMsg getAddress(@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }

        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("uid",claims.getId());

        return new CodeMsg(service.list(queryWrapper));
    }

    @PostMapping
    public CodeMsg add(@RequestHeader String token,@RequestBody Address address){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        address.setUid(Integer.parseInt(claims.getId()));
        System.out.println(address);
        return new CodeMsg(service.save(address));

    }

    @DeleteMapping("/{id}")
    public CodeMsg delete(@PathVariable Integer id,@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }

        if (id < 1){
            return new CodeMsg(201,"id不合法");
        }

        return new CodeMsg(service.removeById(id));
    }

    @PutMapping
    public CodeMsg putaddress(@RequestHeader String token,@RequestBody Address address){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }

        return new CodeMsg(service.updateById(address));
    }
}
